new Vue({
    el: '#permissions',
    data: function () {
        return {
            searchForm: { //查询条件
                searchDate: this.getYesterday(),
                branch: '',
                cso: ''
            },
            branchs: [],//分公司
            CSOs: [],
            currentpage:1,//当前页数
            pageBean:[//分页参数列表
            ],
            DDFB: false,
            activeName: 'map',
            myChart: '',
            noData: false, //暂无数据
            APE: '',
            YCB: '',
            //地图名称
            mapName: '',
            //省份排名
            xAxisProvinceRanked: {data: []}, 
            seriesProvinceRanked: [{
                type: 'bar',
                label: {
                    normal: {
                        show: true,
                        position: 'insideTop',
                        offset: [0, -20],
                        color: '#e6061f'
                    }
                },
                data: [],
                barWidth: '40%'
            }],
            //机构排名
            xAxisCSORanked: {data: []}, 
            seriesCSORanked: [{
                type: 'bar',
                label: {
                    normal: {
                        show: true,
                        position: 'insideTop',
                        offset: [0, -20],
                        color: '#e6061f'
                    }
                },
                data: [],
                barWidth: '40%'
            }],
            //地图
            mapdata: [],
            city: [],
            //有CSO的省会
            provinces: {},
            //渠道分布
            legendChannelsDistribution: [],
            seriesChannelsDistribution: [{
                type: 'pie',
                center: ['40%', '50%'],
                radius: [120, 180],
                label: {
                	formatter: function(params) {
                		console.info("----"+params)
                		return params.name + ':' + params.data.value+"万元"+"，占比:" + params.percent+"%"
                	}
                },
                data: []
            }],
            //产品分布
            productDistribution: [],
            seriesProductDistribution: [{
                type: 'pie',
                center: ['40%', '50%'],
                radius: [120, 180],
                label: {
                	formatter: function(params) {
                		console.info("----"+params)
                		return  params.data.value+"万元"+"，占比:" + params.percent+"%"
                	}
                },
                data: []
            }],
            DDTable: [],
            bigPolicy: []
        }
    },
    mounted: function () {
    	this.getBranch()
        this.resizeChart()
        this.initChartMap(this.mapName)
        this.query()
    },
    methods: {
    	/**下一页 上一页按钮 */
      	handleCurrentChange:function(val){
      		this.currentpage=val;
      		this.pageChange(val)
      	},
      //获取分公司
        getBranch:function(){
            var _this = this;
            $.ajax({
                url: '/statistical/objectif/findBranch',
                type: 'get',
                dataType: 'json',
                async: false,//同步
                success: function (res) {
                	_this.branchs = res.data
                },
                error: function (err) {
                	if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                    errorMessage(_this.$message, '查询分公司出错！错误代码：'+(err.status))
                }
            })
        },
    	//昨天日期
    	getYesterday: function(){
        	var d = new Date();
        	var t = d.getTime()-1000*60*60*24;
        	var yesterday = new Date(t);
        	return yesterday;
        },
        /**
         * 改变分公司
         * @param value
         */
    	changeBranch: function (value) {
    		this.searchForm.cso = ""
        		var _this = this;
                if(value!=''){
                	$.ajax({
                        url: '/statistical/objectif/findCSO',
                        data:{"data":value},
        	            type: 'post',
        	            dataType: 'json',
                        success: function (res) {
                        	_this.CSOs = res.data;
                        },
                        error: function (err) {
                        	if(err.responseJSON.message=="session clean"){
                                errorMessage(_this.$message, '登陆已失效重新登陆!');
                                toLogin();
                                return;
                            }
                            errorMessage(_this.$message, '查询支公司出错！错误代码：'+(err.status))
                        }
                    })
                }
        },
        //清空
    	resetSearchForm: function (formName) {
    	    this.searchForm.searchDate = this.getYesterday()
      		this.$refs[formName].resetFields()
      	},
      	query: function(){
      		var _this = this;
      		 _this.mapName = "";
      		if(_this.searchForm.branch=="" && _this.searchForm.cso!=""){
      			errorMessage(_this.$message, "请选择分公司");
      			return;
      		}
        	if(_this.searchForm.searchDate==null){
        		_this.searchForm.searchDate = this.getYesterday()
        	}
        	if (this.myChart && this.myChart.dispose) {
        		this.myChart.showLoading()
        	}
        	console.info('调用查询:'+JSON.stringify(_this.searchForm))
        	$.ajax({
	             url: '/statistical/advances/findData',
	             data:{"data":JSON.stringify(_this.searchForm)},
	             type: 'post',
	             async: true,
	             dataType: 'json',
	             success: function (res) {
	            	 console.info(res);
	            	 //地图
	            	 _this.mapdata = res.data.mapDataList
            		 _this.city = res.data.cityList
            		 _this.provinces = res.data.provinces
	            	 
            		 _this.APE = res.data.apeData;
	            	 _this.YCB = res.data.ycbData;
	            	 
	            	 if(_this.searchForm.branch!=''){
	            		 for(var key in res.data.provinces){
		            		  _this.mapName = key
		            	 }
	            	 }
	            	 
	            	 //省份排名
	            	 _this.xAxisProvinceRanked.data = res.data.xAxisProvinceRankedData
		             _this.seriesProvinceRanked[0].data = res.data.seriesProvinceRankedData
		             
		             //机构排名
	            	 _this.xAxisCSORanked.data = res.data.xAxisCSORankedData
		             _this.seriesCSORanked[0].data = res.data.seriesCSORankedData
		             
		             //渠道分布
		             _this.legendChannelsDistribution = res.data.legendChannelsDistribution
		             _this.seriesChannelsDistribution[0].data = res.data.seriesChannelsDistributionData
		             
		             //产品分布
		             _this.productDistribution = res.data.productDistribution;
		             _this.seriesProductDistribution[0].data = res.data.seriesProductDistributionData;
		             
		             //大单分布
		             _this.bigPolicy = res.data.bigPolicyList;
		             
		             var page = {}
		             page['totalNumber'] = res.data.totalNumber
		             page['pageSize'] = res.data.pageSize
		             _this.pageBean = page
		             
		           //前端大单分页
		             _this.pageChange(1)
		             
		             _this.draw(_this.activeName)
	             }
        	})
        	
      	},
      	handleClick: function (tab, event) { //tab切换
      		this.draw(tab.name)
      	},
      	pageChange: function (val){
      		var _this = this;
      		var cur_page = val
      		var page_size = _this.pageBean.pageSize
      		var total_number = _this.pageBean.totalNumber
      		
      		console.info(cur_page+"-"+page_size+"-"+total_number)
      		
      		var size = 0
      		if(total_number/cur_page <= page_size){
      			size = (cur_page-1)*page_size+total_number%page_size
      		} else {
      			size = cur_page*page_size;
      		}
      		_this.DDTable = []
      		for(var i=(cur_page-1)*page_size;i<size;i++){
      			_this.DDTable.push(_this.bigPolicy[i])
      			console.info(_this.bigPolicy[i])
      		}
      		
      	},
      	draw: function (tabname) { 
            switch(tabname) {
                case 'provinceRanked': 
                    this.initChartBar('', this.xAxisProvinceRanked, '', this.seriesProvinceRanked)
                    this.DDFB = false
                    this.myChart.hideLoading()
                    break;
                case 'csoRanked': 
                    this.initChartBar('', this.xAxisCSORanked, '', this.seriesCSORanked)
                    this.DDFB = false
                    this.myChart.hideLoading()
                    break;
                case 'map': 
                    this.initChartMap(this.mapName)
                    this.DDFB = false
                    this.myChart.hideLoading()
                    break;
                case 'channelsDistribution': 
                    this.initChartPie('', this.legendChannelsDistribution, this.seriesChannelsDistribution)
                    this.DDFB = false
                    this.myChart.hideLoading()
                    break;
                case 'productDistribution': 
                    this.initChartPie('', this.productDistribution, this.seriesProductDistribution)
                    this.DDFB = false
                    this.myChart.hideLoading()
                    break;
                case 'DDDistribution': 
                    this.DDFB = true
                    break;
            }
        },
        resizeChart: function () { //计算eChart画布尺寸
            this.$refs['myChart'].style.width = document.querySelector('.card-body').offsetWidth - 230 + 'px'
            this.$refs['myChart'].style.height = 600 + 'px'
        },
        initChartBar: function (title, xAxis, legendData, series) { //柱状图
            var _this = this
            this.myChart = echarts.init(this.$refs['myChart'])
            var option = {
                title: {
                    text: title,
                    left: 'center',
                    textStyle: {
                        fontSize: 22
                    }
                },
                color: ['#d2001f', '#2a4556', '#4fa3ab'], //调色盘
                legend: {
                    data: legendData, //图例项名称
                    orient: 'horizontal', //图例列表的布局朝向
                    right: 60
                },
                tooltip: { //提示框组件
                    show: true,
                    trigger: 'axis',
                    formatter: function (params) {
                    	if (params.length == 3) {
                    		return '<div class="echartsParams"><div>' + params[0].name + '</div><div>' + params[0].seriesName + ': ' + params[0].value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + '万元</div><div>' + params[1].seriesName + ': ' + params[1].value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + '万元</div><div>' + params[2].seriesName + ': ' + params[2].value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + '万元</div></div>'
                    	} else {
                    		return '<div class="echartsParams"><div>' + params[0].name + ': ' + params[0].value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + '万元</div></div>'
                    	}
                    	
                    }
                },
                toolbox: {
                    show: true,
                    right: 20,
                    feature: {
                        saveAsImage: { //保存图片
                            type: 'png',
                            name: title,
                            title: '保存为图片',
                            show: true
                        }
                    }
                },
                grid: {
                    left: 45, //离容器左侧距离
                    right: 30,
                    bottom: 100
                },
                xAxis: xAxis,
                yAxis: [{name: '单位：万元', nameTextStyle:{color:'#000'}}],
                dataZoom: [{
                    type: 'slider',
                    show: true,
                    xAxisIndex: [0],
                    start: 0,
                    end: 100,
                    bottom:0
                }],
                series: series
            }
            this.myChart.clear()
            this.myChart.setOption(option)
            window.onresize = function () {
                _this.resizeChart()
                _this.myChart.resize()
            }

            if (series.length <=1 && series[0].data.length <1) {
            	this.myChart.clear()
            	this.noData = true
            } else { 
            	this.noData = false
            }
        },
        initChartPie: function (title, legendData, series) { //饼图
            var _this = this
            this.myChart = echarts.init(this.$refs['myChart'])
            var option = {
                title: {
                    text: title,
                    left: 'center',
                    textStyle: {
                        fontSize: 22
                    }
                },
                //color: ['#ef8f30', '#fbd043', '#f6aa39', '#dc6041', '#f49e4a', '#f8c455', '#eb7c2b'], //调色盘
                legend: {
                    data: legendData, //图例项名称
                    orient: 'horizontal', //图例列表的布局朝向
//                    right: 60,
                    bottom: 0
                },
                tooltip: { //提示框组件
                    show: true,
                    trigger: 'item',
                    formatter: '{b}: {c}万元<br>占比：{d}%'
                },
                toolbox: {
                    show: true,
                    right: 20,
                    feature: {
                        saveAsImage: { //保存图片
                            type: 'png',
                            name: title,
                            title: '保存为图片',
                            show: true
                        }
                    }
                },
                series: series
            }
            this.myChart.clear()
            this.myChart.setOption(option)
            window.onresize = function () {
                _this.resizeChart()
                _this.myChart.resize()
            }
            if (series.length <=1 && series[0].data.length <1) {
            	this.myChart.clear()
            	this.noData = true
            } else { 
            	this.noData = false
            }
        },
            
            
        getCityJSON: function (name, seriesName) {
        	var _this = this
        	if( name in _this.provinces ){
                //如果点击的是34个省、市、自治区，绘制选中地区的二级地图
                $.getJSON('/assets/js/vue/map/province/'+ _this.provinces[name] +'.json', function(data){
                    echarts.registerMap(name, data);
                    var d = _this.city;
                    for( var i=0;i<data.features.length;i++ ){
                        d.push({
                            name:data.features[i].properties.name
                        })
                    }
                    _this.renderMap(name, d, seriesName);
                });
            }
            else{
            	$.getJSON('/assets/js/vue/map/china.json', function(data){
                    echarts.registerMap('china', data);
                    _this.renderMap('china', _this.mapdata);
                });
            }
        },
        renderMap: function (map, data, mapData){
            //初始化绘制全国地图配置
        	var _this = this
            var option = {
                title : {
                    text: '预收APE' + _this.APE + '　　　预承保客户数' + _this.YCB,
                    left: 'center',
                    textStyle:{
                        fontSize:20,
                    }
                },
                visualMap: {
                	type: 'continuous',
                    min: 0,
                    max: 100,
                    left: 'left',
                    top: 'bottom',
                    text: ['高', '低'],
                    realtime: false,
                    calculable: true,
                    inRange: {
                        color: ['#f5a705', '#e6061f'],
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        if (!isNaN(params.value)) {
                            if (mapData !== 'china') {
                            	return params.name + '分公司<br><small>预收APE：</small>' + params.value + '万元'
                            } else {
                            	if(params.name=="深圳" || params.name=="苏州"){
                            		return params.name + '分公司<br><small>预收APE：</small>' + params.value + '万元'
                            	}else{
                            		return params.name + '中心支公司<br><small>预收APE：</small>' + params.value + '万元'
                            	}
                            }
                            
                        }
                    }
                },
                toolbox: {
                    show: true,
                    right: 20,
                    feature: {
                        saveAsImage: { //保存图片
                            type: 'png',
                            name: '预收业绩地图',
                            title: '保存为图片',
                            show: true
                        }
                    }
                },
                animationDuration:1000,
                animationEasing:'cubicOut',
                animationDurationUpdate:1000
                 
            };
            option.series = [ 
                {
                    name: map,
                    type: 'map',
                    mapType: map,
                    roam: false,
                    nameMap:{
                        'china':'中国'
                    },
                    label: {
                        normal:{
                            show:true,
                            textStyle:{
                                color:'#333',
                                fontSize:13
                            }  
                        },
                        emphasis: {
                            show: true,
                            textStyle:{
                                color:'#fff',
                                fontSize:13
                            }
                        }
                    },
                    itemStyle: {
                        normal: {
                            areaColor: '#d0d0d0',
                            borderColor: '#fbfbfb'
                        },
                        emphasis: {
                            areaColor: 'darkorange'
                        }
                    },
                    data:data
                }   
            ];

            //渲染地图
            _this.myChart.clear()
            _this.myChart.setOption(option);
            window.onresize = function () {
                _this.resizeChart()
                _this.myChart.resize()
            }
            if (data.length <1) {
            	_this.myChart.clear()
            	_this.noData = true
            } else { 
            	_this.noData = false
            }
        },
        initChartMap: function (mapName) { //地图
            var _this = this
            this.myChart = echarts.init(this.$refs['myChart'])
            //绘制全国地图
            _this.getCityJSON(mapName, 'china')

            //地图点击事件
            this.myChart.on('click', function (params) {
                console.log(params)
                _this.getCityJSON(params.name, params.seriesName)
            });
        }
    }
})